﻿SmitearWebGL.Events.EventPool = Class.extend(
{
	/******** constructor ********/

	init : function()
	{
		this._registClass( "SmitearWebGL.Events.EventPool" );

		this._pool = {};
	}
	,

	/******** private method ********/

	_bind : function( type, instance, callBackFunction )
	{
		if ( this._pool[type] == undefined )
		{
			this._pool[type] = [
			{
				instance : instance,
				callBackFunction : callBackFunction
			}
			];
		}
		else
		{
			this._pool[type].push(
			{
				instance : instance,
				callBackFunction : callBackFunction
			}
			);
		}

		return true;
	}
	,
	_unbind : function( type, callBackFunction )
	{
		if ( this._pool[type] == undefined )
		return false;
		else
		{
			var i = 0, found = false;
			var session = this._pool[type];
			for ( ; i < session.length; ++ i )
			{
				var _callBackFunction = session[i].callBackFunction;

				if ( _callBackFunction === callBackFunction )
				{
					session[i].instance = null;
					session[i].callBackFunction = null;
					session.splice( i, 1 );
					found = true;
					break;
				}
			}

			if ( ! found )
			return false;
			else
			{
				if ( 0 == session.length ) eval( "delete this._pool." + type );
				return true;
			}
		}
	}
	,
	_invoke : function( event )
	{
		var session = this._pool[event.type];

		if ( session != undefined )
		{
			for ( var i = 0; i < session.length; ++ i )
			{
				var _instance = session[i].instance;
				var _callBackFunction = session[i].callBackFunction;
				
				event.currentTarget = _instance;
				
				_instance.__evtCallBackFunction__ = _callBackFunction;
				_instance.__evtCallBackFunction__( event );
				
				delete _instance.__evtCallBackFunction__;
			}
		}
	}
}
);